package com.ruoyi.point.watcher.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.ruoyi.point.pojo.OperationLog;
import com.ruoyi.framework.pojo.VirInfo;
import com.ruoyi.point.service.IOperationLogService;
import com.ruoyi.framework.point.PointTable;
import com.ruoyi.framework.watcher.IWatcher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.List;

@Slf4j
@Component
public class OperationLogWatcher implements IWatcher {

    @Autowired
    private PointTable pointTable;

    private static final String NAME_INFO = "OperationLog";

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().registerModule(new JavaTimeModule());

    @Autowired
    private IOperationLogService operationLogService;

    @PostConstruct
    public void init() {
        pointTable.addReadWatcher(NAME_INFO,this);
        pointTable.addWriteWatcher(NAME_INFO,this);
    }
    @Override
    public List<? extends VirInfo> selectPointInfo(String key, String parameter, Object value) {
        JsonNode jsonNode = null;
        String[] split = parameter.split("\\.");
        String parameters = split[0].replace("$", "");
        if (parameters.equals("all")){
            return operationLogService.selectOperationLogList(null);
        } else if (parameters.equals("read")){
            try {
                jsonNode = OBJECT_MAPPER.readTree(value.toString());
                OperationLog operationLog = OBJECT_MAPPER.readValue(jsonNode.traverse(),OperationLog.class);
                return operationLogService.selectOperationLogList(operationLog);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    @Override
    public void updatePointTableValue(String key, Object jsonNode) {

    }
}
